<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2014/10/11
 * Time: 15:30
 * 后台用户权限验证系统
 */
class AdminAuthIdentity extends CUserIdentity{
    const LOGIN_SUCCESS = 1001;//登陆成功
    const LOGIN_NO_GROUP = 1002;//用户没有分配用户组
    const LOGIN_NO_PROJECT = 1003;//用户没有分配项目
    const LOGIN_FAILD = 1000;//登陆失败
    /**
     * @return bool|void
     * 后台用户登陆
     * 没有分配用户组和没有分配项目权限的用户登陆失败
     */
    public function authenticate(){
        if ($userinfo = ManageUser::model()->login($this->username, $this->password)){
            Yii::app()->session['username'] = $userinfo->username;
            Yii::app()->session['user_id'] = $userinfo->user_id;
            Yii::app()->session['group_id'] = $userinfo->group_id;
            if (!$userinfo->group_id) {
                return self::LOGIN_NO_GROUP;
            }
            //查询用户项目权限
            $project_ids = ManageUserProject::model()->getByUser($userinfo->user_id);

            if ($project_ids == ManageUserProject::ALL_PROJECT) 
            {
                Yii::app()->session['project_id'] = ManageUserProject::ALL_PROJECT;
            } else {
                //如果没有项目，那么用户登陆后不再判断是否有项目，直接查询
                if (empty($project_ids)) {
                    //return self::LOGIN_NO_PROJECT;
                    Yii::app()->session['project_id'] = 0;
                } else {
                    Yii::app()->session['project_id'] = join(',', $project_ids);
                }
            }

            //查找用户组权限
            $group_auth = ManageGroup::model()->findByPk($userinfo->group_id);
            Yii::app()->session['group_auth'] = $group_auth->group_auth;
            return self::LOGIN_SUCCESS;
        }
        return self::LOGIN_FAILD;
    }
    
    /**
     * 检查用户是否有某个操作的权限
     */
    public static function checkauth($controller, $action){
        $group_auth = Yii::app()->session['group_auth'];
        $auth = $controller.'.'.$action;
        if ($group_auth == '*') {
            return true;
        }
        //不用判断权限的方法，主要用于异步获取操作
        $except_auth = 'network.getnet,checknetwork';
        if (stripos($xcept_auth, $auth) !== false) {
            return true;
        }
        if (stripos($group_auth, $auth) !== false) {
            return true;
        }
        
        return false;
    }
}
